package com.daniel.cloud.controller;

import com.daniel.cloud.config.PatternProperties;
import com.daniel.cloud.service.UserService;
import com.daniel.cloud.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author 10192
 * @return com.daniel.cloud.controller
 * @date 2022/5/27 9:40
 * @versions 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //添加discovery
    //注意此处导入的是接口
    @Autowired
    private DiscoveryClient discoveryClient;


    @Autowired
    private PatternProperties properties;

    @GetMapping("now")
    public String now() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat()));
    }

    @GetMapping("prop")
    public PatternProperties properties() {
        return properties;
    }

    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id) {

        return userService.queryById(id);
    }

    @GetMapping("/lb")
    public String getBalancedServer(HttpServletRequest request, @RequestHeader(value = "goal", required = false) String goal) {
        System.out.println(goal);
        String localAddr = request.getLocalAddr();
        int localPort = request.getLocalPort();
        String str = localAddr + ":" + localPort;
        return str;
    }

    @GetMapping("/all")
    public List<User> queryById() {
        return userService.findAll();
    }

    @GetMapping(value = "/discovery")
    public Object getDiscovery() {
        //        拿到所有注册服务的信息
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            System.out.println("########element:" + service);
        }
        //        拿到指定服务名称的所有的服务注册信息比如8800模块，它与8801模块的名称都相同
        //        所以这里返回的是list
        List<ServiceInstance> instances = discoveryClient.getInstances("AAUSERSERVICE");
        for (ServiceInstance instance : instances) {
            System.out.println("服务id：" + instance.getInstanceId() +
                    "\t服务主机：" + instance.getHost() +
                    "\t服务端口：" + instance.getPort() +
                    "\t服务Url：" + instance.getUri()
            );
        }
        return this.discoveryClient;
    }
}